//
//  eg.swift
//  DaRings
//
//  Created by 尹琼 on 2023/2/27.
//

import UIKit
import HandyJSON

/// 日常目标达成记录
open class DailyExerciseAchievement: NSObject, HandyJSON {
    
    private static let userDefaultKey = "DailyExerciseAchievement"
    
    public var date: Date = Date()
    
    /// 锻炼时长目标达成次数
    public var time: Int = 0
    
    /// 是否可弹出时长目标达成弹窗
    public var timeAlertAble: Bool = true
    
    /// 卡路里目标达成次数
    public var calorie: Int = 0
    
    
    /// 是否可弹出卡路里目标达成弹窗
    public var calorieAlertAble: Bool = true
    

    /// 步数目标达成次数
    public var step: Int = 0
    
    /// 是否可弹出卡路里目标达成弹窗
    public var stepAlertAble: Bool = true
    

    required public override init() {
        super.init()
    }
    
    /// 当前存储的设备信息
    /// - Returns: model
    public static func current() ->DailyExerciseAchievement {
        
        let dict = UserDefaults.standard.dictionary(forKey: DailyExerciseAchievement.userDefaultKey)
        let date = Date()
        
        guard let achievementModel = DailyExerciseAchievement.deserialize(from: dict), date.day == achievementModel.date.day else {
            Self.remove()
            let achievementModel = DailyExerciseAchievement()
            return achievementModel
        }
        
        return achievementModel
        
    }
    
    public func save() {
        
        guard let dict = self.toJSON() else {
            UserDefaults.standard.removeObject(forKey: DailyExerciseAchievement.userDefaultKey)
            return
            
        }
        
        if dict.isEmpty {
            Self.remove()
        } else {
            UserDefaults.standard.set(dict, forKey: DailyExerciseAchievement.userDefaultKey)
        }
        
    }
    
    public static func remove() {
        
        UserDefaults.standard.removeObject(forKey: DailyExerciseAchievement.userDefaultKey)
    }
    
    

}
